package com.lse_api.config.log;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lse_api.config.interceptor.CrossInterceptorConfig;
import com.lse_api.entity.ProjectLog;
import com.lse_api.entity.Token;
import com.lse_api.service.ProjectLogService;
import com.lse_api.utils.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 项目日志 log存储
 *
 * @author 祁雪
 */
@Component
public class ProjectLogConfig {

    private static ProjectLogService projectLogService;

    private static HttpServletRequest request;

    @Autowired
    public void setProjectLogService(ProjectLogService projectLogService) {
        ProjectLogConfig.projectLogService = projectLogService;
    }

    @Resource
    public void setRequest(HttpServletRequest request) {
        ProjectLogConfig.request = request;
    }

    /**
     * 存储项目日志
     *
     * @param info
     * @param projectId
     */
    public static void saveProjectLog(String info, int projectId) {

        ProjectLog projectLog = new ProjectLog();

        projectLog.setLogInfo(info);
        projectLog.setId(UUID.getUUIDToStr());
        projectLog.setIpAddress(CrossInterceptorConfig.getIpAddr(request));
        projectLog.setLogTime(new Date());
        projectLog.setUserId(((Token) request.getAttribute("token")).getUsersUid());
        projectLog.setProjectId(projectId);

        projectLogService.save(projectLog);
    }

    /**
     * 清空日志
     *
     * @param projectId
     */
    public static void emptyProjectLog(int projectId) {

        QueryWrapper<ProjectLog> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("project_id", projectId);

        projectLogService.remove(queryWrapper);

    }

}
